package com.javasm.advice;

import com.alibaba.fastjson.JSON;
import com.javasm.domain.ResponseResult;
import com.javasm.exception.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 基于注解的全局异常处理
 *
 */
@ControllerAdvice(annotations = Controller.class)
public class AuthenExceptionAdvice {

    //slf4j日志处理
    private static final Logger logger = LoggerFactory.getLogger(AuthenExceptionAdvice.class);

    /**
     * 只要项目中出现这个异常，就会调用这个方法
     *
     * @param e        接受到异常
     * @param request  利用request和response方便对异常的后后续处理
     * @param response
     * @throws IOException
     */
    @ExceptionHandler({AuthenticationException.class})//AuthenticationException.class的作用是代表异常的类型
    public void handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //普通文本，浏览器会自动转换为json格式
        response.setContentType("application/plain;charset=utf-8");
        PrintWriter writer = response.getWriter();
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
        logger.error(result.toString());
        String errorInfo = JSON.toJSONString(result);
        writer.write(errorInfo);
    }

    @ExceptionHandler({RuntimeException.class})//RuntimeException.class的作用是代表异常的类型
    public void handlerRuntimeException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //普通文本，浏览器会自动转换为json格式
        response.setContentType("application/plain;charset=utf-8");
        PrintWriter writer = response.getWriter();

        ResponseResult result = new ResponseResult(HttpStatus.BAD_REQUEST.value(), e.getMessage());
        logger.error(result.toString());
        String errorInfo = JSON.toJSONString(result);
        writer.write(errorInfo);
    }
}